package com.Xht.www.dao;

import com.Xht.www.po.UserWalletBalancePO;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class UserWalletBalanceDAO extends BaseDAO {
    private static final Logger LOGGER = Logger.getLogger(UserWalletBalanceDAO.class.getName());

    // 插入用户钱包余额信息
    public boolean insertUserWalletBalance(UserWalletBalancePO po) {
        if (!isValidPO(po)) {
            return false;
        }
        String sql = "INSERT INTO user_wallet_balance (wallet_id, user_id, total_amount, recharge_amount, consumption_amount, top_up_amount, recharge_audit_status, recharge_reason) VALUES (?,?,?,?,?,?,?,?)";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, po.getWalletId());
            pstmt.setInt(2, po.getUserId());
            pstmt.setBigDecimal(3, po.getTotalAmount());
            pstmt.setBigDecimal(4, po.getRechargeAmount());
            pstmt.setBigDecimal(5, po.getConsumptionAmount());
            pstmt.setBigDecimal(6, po.getTopUpAmount());
            pstmt.setString(7, po.getRechargeAuditStatus());
            pstmt.setString(8, po.getRechargeReason());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "插入用户钱包余额信息失败", e);
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 根据钱包ID删除用户钱包余额信息
    public boolean deleteUserWalletBalance(int walletId) {
        String sql = "DELETE FROM user_wallet_balance WHERE wallet_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, walletId);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 根据钱包ID查询用户钱包余额信息
    public UserWalletBalancePO getUserWalletBalance(int walletId) {
        String sql = "SELECT * FROM user_wallet_balance WHERE wallet_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, walletId);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                UserWalletBalancePO po = new UserWalletBalancePO();
                po.setWalletId(rs.getInt("wallet_id"));
                po.setUserId(rs.getInt("user_id"));
                po.setTotalAmount(rs.getBigDecimal("total_amount"));
                po.setRechargeAmount(rs.getBigDecimal("recharge_amount"));
                po.setConsumptionAmount(rs.getBigDecimal("consumption_amount"));
                po.setTopUpAmount(rs.getBigDecimal("top_up_amount"));
                po.setRechargeAuditStatus(rs.getString("recharge_audit_status"));
                po.setRechargeReason(rs.getString("recharge_reason"));
                return po;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return null;
    }

    // 更新用户钱包余额信息
    public boolean updateUserWalletBalance(UserWalletBalancePO po) {
        if (!isValidPO(po)) {
            return false;
        }
        String sql = "UPDATE user_wallet_balance SET user_id = ?, total_amount = ?, recharge_amount = ?, consumption_amount = ?, top_up_amount = ?, recharge_audit_status = ?, recharge_reason = ? WHERE wallet_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, po.getUserId());
            pstmt.setBigDecimal(2, po.getTotalAmount());
            pstmt.setBigDecimal(3, po.getRechargeAmount());
            pstmt.setBigDecimal(4, po.getConsumptionAmount());
            pstmt.setBigDecimal(5, po.getTopUpAmount());
            pstmt.setString(6, po.getRechargeAuditStatus());
            pstmt.setString(7, po.getRechargeReason());
            pstmt.setInt(8, po.getWalletId());
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 检验PO对象的输入是否合法有效
    private boolean isValidPO(UserWalletBalancePO po) {
        if (po == null) {
            return false;
        }
        if (po.getWalletId() == null || po.getUserId() == null) {
            return false;
        }
        if (po.getTotalAmount() == null || po.getRechargeAmount() == null || po.getConsumptionAmount() == null || po.getTopUpAmount() == null
                || po.getRechargeAuditStatus() == null || po.getRechargeReason() == null) {
            return false;
        }
        return true;
    }

    // 获取所有审核中的用户钱包信息
    public List<UserWalletBalancePO> getAllPendingRecharges() {
        String sql = "SELECT * FROM user_wallet_balance WHERE recharge_audit_status = '审核中'";
        Connection connection = getConnection();
        List<UserWalletBalancePO> pendingList = new ArrayList<>();
        try (Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                UserWalletBalancePO po = new UserWalletBalancePO();
                po.setWalletId(rs.getInt("wallet_id"));
                po.setUserId(rs.getInt("user_id"));
                po.setTotalAmount(rs.getBigDecimal("total_amount"));
                po.setRechargeAmount(rs.getBigDecimal("recharge_amount"));
                po.setConsumptionAmount(rs.getBigDecimal("consumption_amount"));
                po.setTopUpAmount(rs.getBigDecimal("top_up_amount"));
                po.setRechargeAuditStatus(rs.getString("recharge_audit_status"));
                po.setRechargeReason(rs.getString("recharge_reason"));
                pendingList.add(po);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return pendingList;
    }

    // 更新审核状态
    public boolean updateRechargeStatus(int walletId, String status) {
        String sql = "UPDATE user_wallet_balance SET recharge_audit_status = ? WHERE wallet_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setString(1, status);
            pstmt.setInt(2, walletId);
            int rows = pstmt.executeUpdate();
            return rows > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            releaseConnection(connection);
        }
    }

    // 根据用户ID查询钱包信息
        public UserWalletBalancePO getUserByUserId(int userId) {
        String sql = "SELECT * FROM user_wallet_balance WHERE user_id = ?";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    UserWalletBalancePO po = new UserWalletBalancePO();
                    po.setWalletId(rs.getInt("wallet_id"));
                    po.setUserId(rs.getInt("user_id"));
                    po.setTotalAmount(rs.getBigDecimal("total_amount"));
                    po.setRechargeAmount(rs.getBigDecimal("recharge_amount"));
                    po.setConsumptionAmount(rs.getBigDecimal("consumption_amount"));
                    po.setTopUpAmount(rs.getBigDecimal("top_up_amount"));
                    po.setRechargeAuditStatus(rs.getString("recharge_audit_status"));
                    po.setRechargeReason(rs.getString("recharge_reason"));
                    return po;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            releaseConnection(connection);
        }
        return null;
    }


    // 检查用户是否有审核中的充值记录
    public boolean hasPendingRecharge(int userId) {
        String sql = "SELECT COUNT(*) FROM user_wallet_balance WHERE user_id =? AND recharge_audit_status = '审核中'";
        Connection connection = getConnection();
        try (PreparedStatement pstmt = connection.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    int count = rs.getInt(1);
                    return count > 0;
                }
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "检查审核中的充值记录失败", e);
        } finally {
            releaseConnection(connection);
        }
        return false;
    }

    //获取下一个钱包
    public Integer getNextWalletId() {
        String sql = "SELECT MAX(wallet_id) FROM user_wallet_balance";
        Connection connection = getConnection();
        try (Statement stmt = connection.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            if (rs.next()) {
                int maxId = rs.getInt(1);
                // 如果表中没有记录，MAX返回0，所以下一个ID应该是1
                return maxId + 1;
            }
        } catch (SQLException e) {
            LOGGER.log(Level.SEVERE, "获取下一个钱包ID失败", e);
        } finally {
            releaseConnection(connection);
        }
        return null; // 如果发生错误或表中没有记录，返回null
    }
}